package com.app.piemoment.api;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.app.piemoment.config.Config;
import com.app.piemoment.entity.LoginInfo;
import com.app.piemoment.entity.PieUser;
import com.app.piemoment.net.HttpResult;
import com.app.piemoment.net.HttpResultJson;
import com.app.piemoment.net.NetService;

public class UserAPI extends BaseApi {

	public UserAPI(Context context) {
		super(context);
	}

	/**
	 * 修改个人的问题
	 * 
	 * @param requestCode
	 * @param context
	 */
	private static String newName = "image.jpg";
	private static String actionUrl = "http://dev.piemoment.com/api/demo/view/users#rest_users_photos_post";
	private static String uploadUrlString = "/api/rest/users/{puid}/photos.json";

	public static void uploadFile(String uploadFile) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(actionUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; "
					+ "name=\"file1\";filename=\"" + newName + "\"" + end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(uploadFile);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 将Response显示于Dialog */
			Log.e("", "上传成功" + b.toString().trim());
			;
			/* 关闭DataOutputStream */
			ds.close();
		} catch (Exception e) {
			Log.e("", "上传失败" + e);

		}
	}

	public void setPersonInfo(final int requestCode, final Context context,
			final PieUser pieuser, final String code) {

		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);
				List<NameValuePair> params = new ArrayList<NameValuePair>();

				params.add(new BasicNameValuePair("token", LoginInfo
						.getInstance().getAccess_token()));
				params.add(new BasicNameValuePair(PieUser.birth_place_S,
						pieuser.getBirth_place()));
				params.add(new BasicNameValuePair(PieUser.birthday_S, pieuser
						.getBirthday()));
				params.add(new BasicNameValuePair(PieUser.current_city_S,
						pieuser.getCurrent_city()));
				params.add(new BasicNameValuePair(PieUser.degree_S, pieuser
						.getDegree()));
				params.add(new BasicNameValuePair(PieUser.domain_S, pieuser
						.getDomain()));
				params.add(new BasicNameValuePair(PieUser.first_name_S, pieuser
						.getFirst_name()));
				params.add(new BasicNameValuePair(PieUser.height_S, pieuser
						.getHeight()));
				params.add(new BasicNameValuePair(PieUser.nickname_S, pieuser
						.getNickname()));
				params.add(new BasicNameValuePair(PieUser.occupation_S, pieuser
						.getOccupation()));
				params.add(new BasicNameValuePair(PieUser.presentation_S,
						pieuser.getPresentation()));
				params.add(new BasicNameValuePair(PieUser.school_S, pieuser
						.getSchool()));
				params.add(new BasicNameValuePair(PieUser.sex_S, pieuser
						.getSex()));
				params.add(new BasicNameValuePair(PieUser.surnname_S, pieuser
						.getSurnname()));

				params.add(new BasicNameValuePair(PieUser.weight_S, pieuser
						.getWeight()));

				HttpResultJson result = NetService
						.httpPutReturnJson(
								context,
								Config.HOME_URL
										+ String
												.format(
														Config.SET_PERSONINFO_URL,
														code), params);

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					JSONObject jsonObject = result.getJson();
					apiResult.setJsonEntity(jsonObject);
				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}

			@Override
			protected void onPreExecute() {
				if (returnResultListener == null) {
					return;
				}
				returnResultListener.onReturnLoading(requestCode);
				super.onPreExecute();
			}

		}.execute();
	}

	/**
	 * 
	 * 
	 * @param requestCode
	 * @param context
	 */
	public void setExpectationsInfo(final int requestCode,
			final Context context, final PieUser pieuser, final String code) {

		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);
				List<NameValuePair> params = new ArrayList<NameValuePair>();

				// public static final String height_min_s = "height_min";
				// public static final String height_ideal_s = "";
				// public static final String = "height_max";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";
				// public static final String = "";

				params.add(new BasicNameValuePair("token", LoginInfo
						.getInstance().getAccess_token()));
				params.add(new BasicNameValuePair(PieUser.height_min_s, pieuser
						.getHeight_min()));
				params.add(new BasicNameValuePair(PieUser.height_ideal_s,
						pieuser.getHeight_ideal()));
				params.add(new BasicNameValuePair(PieUser.height_max_s, pieuser
						.getHeight_max()));

				params.add(new BasicNameValuePair(PieUser.age_diff_min_s,
						pieuser.getAge_diff_min()));

				params.add(new BasicNameValuePair(PieUser.age_diff_ideal_s,
						pieuser.getAge_diff_ideal()));
				params.add(new BasicNameValuePair(PieUser.age_diff_max_s,
						pieuser.getAge_diff_max()));
				params.add(new BasicNameValuePair(PieUser.degree_min_s, pieuser
						.getDegree_min()));
				params.add(new BasicNameValuePair(PieUser.degree_ideal_s,
						pieuser.getDegree_ideal()));
				params.add(new BasicNameValuePair(PieUser.dgree_max_s, pieuser
						.getDgree_max()));
				params.add(new BasicNameValuePair(PieUser.location_ideal_s,
						pieuser.getLocation_ideal()));
				params.add(new BasicNameValuePair(PieUser.location_distance_s,
						pieuser.getLocation_distance()));

				HttpResultJson result = NetService
						.httpPutReturnJson(
								context,
								Config.HOME_URL
										+ String
												.format(
														Config.SET_USER_EXPECTATIONS_URL,
														code), params);

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					JSONObject jsonObject = result.getJson();
					apiResult.setJsonEntity(jsonObject);
				} else {
					apiResult.setFailCode(result.getFailCode());
					JSONObject jsonObject = result.getJson();
					apiResult.setJsonEntity(jsonObject);
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}

			@Override
			protected void onPreExecute() {
				if (returnResultListener == null) {
					return;
				}
				returnResultListener.onReturnLoading(requestCode);
				super.onPreExecute();
			}

		}.execute();
	}

	/**
	 * 获取mid 配对信息
	 * 
	 * @param requestCode
	 * @param context
	 */
	public void getMyInfo(final int requestCode, final Context context,
			final String mid) {

		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);
				List<NameValuePair> params = new ArrayList<NameValuePair>();

				try {
					params.add(new BasicNameValuePair("_format", "json"));
					params.add(new BasicNameValuePair("token", URLEncoder
							.encode(LoginInfo.getInstance().getAccess_token(),
									"UTF-8")));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				HttpResultJson result = NetService.httpGetReturnJson(context,
						Config.HOME_URL
								+ String.format(Config.GET_USER_INFO_URL, mid),
						params);

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					JSONObject jsonObject = result.getJson();
					apiResult.setJsonEntity(jsonObject);
				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}

			@Override
			protected void onPreExecute() {
				if (returnResultListener == null) {
					return;
				}
				returnResultListener.onReturnLoading(requestCode);
				super.onPreExecute();
			}

		}.execute();
	}
}
